package com.orange.quickback.system.controller.user.manage;


import com.baomidou.kaptcha.Kaptcha;
import com.orange.quickback.system.api.common.result.QBootResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.security.oauth2.provider.endpoint.TokenEndpoint;
import org.springframework.security.oauth2.provider.token.ConsumerTokenServices;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.security.Principal;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @Author: orange
 * @CreateDate: 2021/11/4
 * @Description:
 */
@RestController
@RequestMapping("/oauth")
public class OauthController {

    @Resource
    private TokenEndpoint tokenEndpoint;

    @Resource
    private Kaptcha kaptcha;

    @GetMapping("/token")
    public QBootResult getAccessToken(Principal principal, @RequestParam Map<String, String> parameters) throws HttpRequestMethodNotSupportedException {
        QBootResult qBootResult;
        kaptcha.validate(parameters.get("code"),300);
        try{
            qBootResult = custom(tokenEndpoint.postAccessToken(principal, parameters).getBody());
        }catch (InvalidGrantException E){
            qBootResult = QBootResult.buildFail("登录失败，请检查用户名与密码");
        }
        return qBootResult;
    }

    @PostMapping("/token")
    public QBootResult postAccessToken(Principal principal, @RequestParam Map<String, String> parameters) throws HttpRequestMethodNotSupportedException {
        QBootResult qBootResult;
        if(parameters.get("code") == null){
            qBootResult = QBootResult.buildFail("登录失败，请输入验证码");
            return qBootResult;
        }
        kaptcha.validate(parameters.get("code"),300);
        try{
            qBootResult = custom(tokenEndpoint.postAccessToken(principal, parameters).getBody());
        }catch (InvalidGrantException E){
            qBootResult = QBootResult.buildFail("登录失败，请检查用户名与密码");
        }
        return qBootResult;
    }

    //定制申请返回实体
    private QBootResult custom(OAuth2AccessToken accessToken) {
        DefaultOAuth2AccessToken token = (DefaultOAuth2AccessToken) accessToken;
        Map<String, Object> data = new LinkedHashMap(token.getAdditionalInformation());
        data.put("accessToken", token.getValue());
        if (token.getRefreshToken() != null) {
            data.put("refreshToken", token.getRefreshToken().getValue());
        }
        return QBootResult.build(data);
    }
}
